package com.byd.dms.serialize;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.byd.dms.entity.Dept;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ListToMapSerializer implements ObjectSerializer {
    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeWriter out = serializer.out;
        
        System.out.println("object = " + object + ", " + object.getClass().getName());
        System.out.println("fieldName = " + fieldName);
        System.out.println("fieldType = " + fieldType);
        if (object == null) {
            //serializer.getWriter().writeNull();
            out.writeNull();
            return;
        }
        
        System.out.println(object instanceof List);
        
        if (object instanceof List) {
            Map<Integer, Dept> map = new HashMap<>();
            List<Dept> list = (List<Dept>) object;
            int i = 0;
            for (Dept dept : list) {
                map.put(i++, dept);
            }
            out.write(JSON.toJSONString(map));
            return;
        }
        
        
        //原来的值code toString的形式
        // String strVal = object.toString();
        String strVal = JSON.toJSONString(object);
        System.out.println("strVal = " + strVal);
        out.write(strVal);
    }
}
